// 公共功能模块
class CommonManager {
    constructor() {
        this.init();
    }

    init() {
        // 检查登录状态
        this.checkAuth();
        
        // 绑定侧边栏切换事件
        this.bindSidebarToggle();
        
        // 更新用户信息显示
        this.updateUserInfo();
    }

    // 检查认证状态
    checkAuth() {
        if (!authManager || !authManager.isLoggedIn) {
            // 如果未登录，跳转到登录页（兼容任意子路径）
            if (!window.location.pathname.includes('login.html')) {
                try {
                    const parts = window.location.pathname.split('/admin/');
                    const base = parts[0] + '/admin/';
                    window.location.href = base + 'login.html';
                } catch (e) {
                    window.location.href = 'login.html';
                }
            }
            return;
        }
    }

    // 绑定侧边栏切换
    bindSidebarToggle() {
        const sidebarToggle = document.getElementById('sidebarToggle');
        const sidebar = document.getElementById('sidebar');
        const mainContent = document.getElementById('mainContent');
        
        if (sidebarToggle && sidebar) {
            sidebarToggle.addEventListener('click', () => {
                sidebar.classList.toggle('collapsed');
                if (mainContent) {
                    mainContent.classList.toggle('expanded');
                }
            });
        }
    }

    // 更新用户信息显示
    updateUserInfo() {
        const usernameElement = document.getElementById('currentUsername');
        if (usernameElement && authManager && authManager.currentUser) {
            usernameElement.textContent = authManager.currentUser.username;
        }
    }

    // 显示加载状态
    showLoading(element, text = '加载中...') {
        if (element) {
            element.innerHTML = `<i class="fas fa-spinner fa-spin mr-2"></i>${text}`;
            element.disabled = true;
        }
    }

    // 隐藏加载状态
    hideLoading(element, originalText) {
        if (element) {
            element.innerHTML = originalText;
            element.disabled = false;
        }
    }

    // 显示成功提示
    showSuccess(message, duration = 3000) {
        this.showToast(message, 'success', duration);
    }

    // 显示错误提示
    showError(message, duration = 5000) {
        this.showToast(message, 'error', duration);
    }

    // 显示提示信息
    showToast(message, type = 'info', duration = 3000) {
        const toast = document.createElement('div');
        const bgColor = type === 'success' ? 'bg-green-500' : 
                       type === 'error' ? 'bg-red-500' : 'bg-blue-500';
        
        toast.className = `fixed top-20 right-4 z-50 px-6 py-3 rounded-lg text-white ${bgColor} shadow-lg transform translate-x-full transition-transform duration-300`;
        toast.textContent = message;
        
        document.body.appendChild(toast);
        
        // 显示动画
        setTimeout(() => {
            toast.classList.remove('translate-x-full');
        }, 100);
        
        // 自动隐藏
        setTimeout(() => {
            toast.classList.add('translate-x-full');
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.parentNode.removeChild(toast);
                }
            }, 300);
        }, duration);
    }

    // 确认对话框
    async confirm(message, title = '确认') {
        return new Promise((resolve) => {
            const modal = document.createElement('div');
            modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
            modal.innerHTML = `
                <div class="bg-white rounded-lg p-6 max-w-sm mx-4">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">${title}</h3>
                    <p class="text-gray-600 mb-6">${message}</p>
                    <div class="flex space-x-3">
                        <button class="flex-1 bg-gray-300 text-gray-700 py-2 px-4 rounded-lg hover:bg-gray-400 transition-colors" onclick="this.closest('.fixed').remove(); resolve(false);">
                            取消
                        </button>
                        <button class="flex-1 bg-blue-500 text-white py-2 px-4 rounded-lg hover:bg-blue-600 transition-colors" onclick="this.closest('.fixed').remove(); resolve(true);">
                            确定
                        </button>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
        });
    }

    // 格式化日期
    formatDate(dateString) {
        const date = new Date(dateString);
        const now = new Date();
        const diff = now - date;
        
        if (diff < 60000) { // 1分钟内
            return '刚刚';
        } else if (diff < 3600000) { // 1小时内
            return `${Math.floor(diff / 60000)}分钟前`;
        } else if (diff < 86400000) { // 1天内
            return `${Math.floor(diff / 3600000)}小时前`;
        } else if (diff < 2592000000) { // 30天内
            return `${Math.floor(diff / 86400000)}天前`;
        } else {
            return date.toLocaleDateString('zh-CN');
        }
    }

    // 生成唯一ID
    generateId() {
        return Date.now().toString(36) + Math.random().toString(36).substr(2);
    }
}

// 初始化公共管理器
const commonManager = new CommonManager();

// 导出供其他模块使用
window.CommonManager = CommonManager;
window.commonManager = commonManager;
